//
//  WQSearchController.m
//  MeterCircle
//
//  Created by 魏强 on 16/6/24.
//  Copyright © 2016年 魏强. All rights reserved.
//

#import "WQSearchController.h"
#import "WQSearchResultViewController.h"
#import "WQSearchBar.h"
#import "UIImage+WQExtension.h"
#import "AppDelegate.h"
#import "KDTabBarController.h"
#import "KDSubscribCell.h"
#import "KDSubscribCellModel.h"
#import "KDSubscripRequestTool.h"
#import "KDCollectRequestTool.h"
#import "KDGetSubscribeListResult.h"
#import "KGDislikeView.h"
#import "KDDeleteNewsParam.h"
#import "KDDetailSubscribController.h"
#import "KDFavorTypeListResult.h"
#import "AlertTableView.h"
#import "KDReportController.h"
#define BACKGROUND_COLOR [UIColor colorWithRed:229/255.f green:238/255.f blue:235/255.f alpha:1.f] // 浅绿色背景
#define TABLE_LINE_COLOR [UIColor colorWithRed:200/255.f green:199/255.f blue:204/255.f alpha:1.f].CGColor // 列表分割线颜色

//static NSString *const kSearchHistory = @"kSearchHistory";
static const float kHeightForFooterInSection = 64;
static const float kMinTableViewHeight = 0.01f;
enum { kMostNumberOfSearchHistories = 15 };
@interface WQSearchController ()<UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate, UISearchBarDelegate,KDSubscribCellDelegate,KDDetailSubscribControllerDelegate,KDReportControllerDelegate>
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *tableView_H_Constraint;

/**  背景蒙板 */
@property (nonatomic, strong) UIView *searchBackgroundView;
@property (nonatomic, weak) WQSearchBar *searchBar;
/** 在navbar和searchbar中间再加一层（避免有些机器无法显示取消按钮）*/
@property (nonatomic, weak) UIView *searchUIView;

@property (nonatomic, strong) UILabel *titleLabel;

@property (nonatomic, strong) NSMutableArray *questionDataSource;
/**  搜索历史 */
@property (nonatomic, strong) NSMutableArray *searchHistories;
/***  判断列表的显示内容是搜索历史记录，还是当前搜索结果*/
@property (assign, getter=isShowResults) BOOL showResults;

/**  所有数据汇总 */
@property (nonatomic, strong) NSArray *infoArr;
/**
 *  加载第几页
 */
@property (nonatomic, copy) NSString *page;
@property (nonatomic, strong) KDSubscribeListParam *param;
@property (nonatomic, retain) NSDateFormatter *fmt;
/**  <#Description#> */
@property (nonatomic, copy) NSString * keyword;


@end
//static CGFloat const searchViewH = 44;
//
//static CGFloat const chooseBtnW = 55;
@implementation WQSearchController
#pragma mark - 懒加载区
- (UIView *)searchBackgroundView{
    if (!_searchBackgroundView) {
        _searchBackgroundView = [[UIView alloc]initWithFrame:self.view.bounds];
        _searchBackgroundView.width=screenW;
        _searchBackgroundView.y = 44;
        _searchBackgroundView.backgroundColor = [UIColor blackColor];
        _searchBackgroundView.alpha = 0;
        UITapGestureRecognizer *recognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideSerchBarWhenTapBackground:)];
        [_searchBackgroundView addGestureRecognizer:recognizer];
    }
    return _searchBackgroundView;
}
/**
 *  懒加载_titleLabel
 *
 *  @return UILabel
 */
- (UILabel *)titleLabel
{
    if (_titleLabel == nil) {
         UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(12, 14, 200, 16)];
        _titleLabel = titleLabel;
        _titleLabel.textColor = APP_TINT_COLOR;
        _titleLabel.font = [UIFont systemFontOfSize:14];
    }
    return _titleLabel;
}
/**
- (UIView *)searchUIView{
    if (!_searchUIView) {
        UIView *searchUIView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, screenW, 44)];
        searchUIView.backgroundColor=WQColor(233, 0, 0);
        KDLog(@"%fwww",screenW);
        _searchUIView = searchUIView;
        [_searchUIView addSubview:self.searchBar];
        
    }
    return _searchUIView;
}*/

- (WQSearchBar *)searchBar{
    if (!_searchBar) {
        WQSearchBar *searchBar = [[WQSearchBar alloc]initWithFrame:CGRectMake(0, 0, 100, 44)];
        KDLog(@"%fwww",screenW);
        _searchBar = searchBar;
        [searchBar setShowsCancelButton:YES animated:YES];
        searchBar.delegate = self;
    }
    return _searchBar;
}
- (NSMutableArray *)questionDataSource {
    if (!_questionDataSource) {
        _questionDataSource = [[NSMutableArray alloc] init];
    }
    return _questionDataSource;
}

- (KDSubscribeListParam *)param
{
    if (!_param) {
        _param = [[KDSubscribeListParam alloc]init];
        _param.method = @"earlywaring/searchEarlywaringInfo";
//        _param.aboutType = @"";
        NSDate *newdate = [[NSDate date] initWithTimeInterval:- (24 *60 * 60 * 6 )sinceDate: [NSDate date]];
        _param.orderType = @"1";
        _param.beginTime = [self.fmt stringFromDate:newdate];
        _param.keywordType = @"0";
        _param.endTime = [self.fmt stringFromDate:[NSDate date]];
//        _param.is_polymer = @"1";
        _param.aboutChildType = @"";
        _param.isRead = @"";
        _param.nation = @"";
        _param.language = @"";
        _param.sourceType = @"";
        _param.emotionType = @"";
        _param.filter = @"";
        _param.keyword = @"";
        KDAccount *account = [KDAccountTool account];
        _param.provinceId = [NSString stringWithFormat:@"%ld",account.provinceId];
        _param.cityId = [NSString stringWithFormat:@"%ld",account.cityId];
        _param.limit = @"20";
        //        _param.
    }
    return _param;
}
- (NSDateFormatter *)fmt
{
    if (!_fmt) {
        _fmt = [[NSDateFormatter alloc]init];
        _fmt.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"];;
        _fmt.dateFormat = @"YYYY-MM-dd HH:mm:ss";
    }
    return _fmt;
}
- (NSString *)page
{
    if (!_page) {
        _page = @"1";
    }
    return _page;
}
- (NSArray *)infoArr
{
    if (!_infoArr) {
        _infoArr = [NSArray new];
    }
    return _infoArr;
}
#pragma mark - 生命周期区
- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        
        self.tableView.height = 0;
        self.searchHistories = [NSMutableArray array];
        self.showResults = NO;
    }
    return self;
}
//- viewWILL
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageWithColor:TEXTFIELD_BACKGROUNDC0LOR] forBarMetrics:UIBarMetricsDefault];
    [self.navigationController.navigationBar setTranslucent:NO];
    self.tabBarController.tabBar.hidden = YES;
}
-(void)dealloc{
    self.tabBarController.tabBar.hidden = NO;
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageWithColor:KDColor] forBarMetrics:UIBarMetricsDefault];
}
- (void)viewDidLoad {
    [super viewDidLoad];

    self.navigationItem.titleView = self.searchBar;
    [self setUpTableView];
    [self.navigationController.navigationBar setNeedsLayout];
    self.navigationController.view.height = 44;
}

#pragma mark - 板块布置区
- (void)setUpTableView
{
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.tag = 1000;
    _tableView.tableFooterView = [UIView new];
    _tableView.separatorColor = BackGroundColor;
    _tableView.backgroundColor = BackGroundColor;
    _tableView.rowHeight = Cell_h;
    if (!iOS7) {
        _tableView.estimatedRowHeight = Cell_h;
    }
    UINib *xib =[UINib nibWithNibName:@"KDSubscribCell" bundle:nil] ;
    [_tableView registerNib:xib forCellReuseIdentifier:@"KDSubscribCell"];
    _tableView.header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadDetailData)];
    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreDetailData)];
    [footer setTitle:@"" forState:MJRefreshStateIdle];
    // 设置footer
    self.tableView.footer = footer;

}

/**
 *  关闭搜索界面
 *
 *  @param completion 关闭完成之后进行的操作
 */
- (void)hide:(void(^)(void))completion{
    UIViewController *ctr = (UIViewController *)self.delegate;
    [ctr.navigationController setNavigationBarHidden:NO animated:YES];
    [UIView animateWithDuration:0.25f animations:^{
        self.navigationController.view.y = 44;
        self.searchBackgroundView.alpha = 0;
    } completion:^(BOOL finished) {
        [self.searchBackgroundView removeFromSuperview];
        self.searchBackgroundView = nil;
        [UIView animateWithDuration:0.2f animations:^{
            self.navigationController.view.alpha = 0;
        } completion:^(BOOL finished) {
            [self.navigationController.view removeFromSuperview];
        }];
    }];
    
    completion ? completion() : nil;
}
-(UIStatusBarStyle)preferredStatusBarStyle{
    return UIStatusBarStyleLightContent;
}

- (void)showInViewController:(UIViewController *)controller{
//    AppDelegate *delegate = ((AppDelegate *)[[UIApplication sharedApplication] delegate]);
//    [delegate.navigationController.view addSubview:self.searchBackgroundView];
    [controller.navigationController.view addSubview:self.searchBackgroundView];
//    KDLog(@"%@", self.searchBackgroundView);
    [controller.navigationController.view addSubview:self.navigationController.view];
    
    //仅修改self.navigationController.view的y,xwh值不变
    self.navigationController.view.y = 44;
    [controller.navigationController setNavigationBarHidden:YES animated:YES];
    
    [UIView animateWithDuration:0.25f animations:^{
        self.navigationController.view.y = 0;
        self.searchBackgroundView.alpha = 0.4f;
    } completion:^(BOOL finished) {
        NSArray *histories = [[NSUserDefaults standardUserDefaults] objectForKey:self.kSearchHistory];
        [self.searchHistories addObjectsFromArray:histories];
        [self reloadViewLayouts];
        [self.searchBar becomeFirstResponder];
        
    }];
    
}
- (void)reloadViewLayouts{
    if (self.isShowResults) {//显示搜索结果
        self.view.height = screenH - 64;
        self.tableView_H_Constraint.constant = self.view.height;
        self.navigationController.view.height = screenH;
        [self.tableView.header beginRefreshing];
    }else{//显示历史搜索记录
        self.tableView_H_Constraint.constant = MIN(self.searchHistories.count * 44 + (self.searchHistories.count > 0 ? kHeightForFooterInSection : 0), screenH - 64);
        if (self.searchHistories.count == 0) {
            //没有历史搜索记录
            self.view.height = CGRectGetMaxY(self.tableView.frame);
            self.navigationController.view.height = self.view.height + 64;
        }else{
            //有历史搜索记录
            self.view.height = screenH - 64;
            self.navigationController.view.height = screenH;
        }
        
    }
//    KDLog(@"%@", self.tableView);
    [self.tableView reloadData];
}

/**
 *  清除搜索记录
 */
- (void)clearHistoriesButtonClicked:(id)sender
{
    [self.searchHistories removeAllObjects];
    [[NSUserDefaults standardUserDefaults] setObject:self.searchHistories forKey:self.kSearchHistory];
    [[NSUserDefaults standardUserDefaults] synchronize];
    [self reloadViewLayouts];
}
/**
 * 删除某个历史搜索关键词
 */
- (void)rightBtnDidClicked:(UIButton *)rightBtn
{
    [self.searchHistories removeObject:self.searchHistories[rightBtn.tag]];
    [[NSUserDefaults standardUserDefaults] setObject:self.searchHistories forKey:self.kSearchHistory];
    [[NSUserDefaults standardUserDefaults] synchronize];
    [self reloadViewLayouts];
}
/**
 *  获取搜索结果列表
 */
- (void)getResultsList:(NSNumber *)startQid
{
    [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
    //构造元素需要使用两个空格来进行缩进，右括号]或者}写在新的一行，并且与调用语法糖那行代码的第一个非空字符对齐：
    NSArray *array = @[
                       @"@iOS程序犭袁 🆑测试1",
                       @"@iOS程序犭袁 🆑测试2",
                       @"@iOS程序犭袁 🆑测试3",
                       @"@iOS程序犭袁 🆑测试4"
                       ];
    self.questionDataSource = [NSMutableArray arrayWithArray:array];
    self.showResults = YES;
    [self reloadViewLayouts];
}
#pragma mark - 事件点击区
- (void)hideSerchBarWhenTapBackground:(id)sender {
    [self hide:nil];
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self hide:nil];
}
#pragma mark - 网络请求区
- (void)loadDetailData{
    self.page = @"1";
    self.param.keyword = self.keyword;
    KDLog(@":%@", self.keyword);
    self.param.page = self.page;
    //    self.param.aboutType = [NSString stringWithFormat:@"%ld",self.model.ID];
    //    param.limit = @"20";
    [KDSubscripRequestTool getSubscribeListWithParam:self.param success:^(KDGetSubscribeListResult *responseObejct) {
        if ([responseObejct.code isEqualToString:@"1"]) {
            self.infoArr = responseObejct.data;
            [self.tableView.header endRefreshing];
            
            [self.tableView reloadData];
        }else if ([responseObejct.code isEqualToString:@"E040110000001"]){
//            [self.navigationController dismissViewControllerAnimated:NO completion:^{
                KDNewfeatureController *new = [[KDNewfeatureController alloc]init];
                __block KDTabBarController*ctr = (KDTabBarController *)[UIApplication sharedApplication].keyWindow.rootViewController;
                [UIApplication sharedApplication].keyWindow.rootViewController = new;
                [ctr removeObserver];
                [ctr removeFromParentViewController];
                ctr = nil;
//            }];
        }else{
            [SVProgressHUD showErrorWithStatus:responseObejct.msg maskType:SVProgressHUDMaskTypeGradient];
        }
        [self.tableView.header endRefreshing];
    } failure:^(NSError *error) {
        [SVProgressHUD showErrorWithStatus:@"网络错误！" maskType:SVProgressHUDMaskTypeGradient];
        [self.tableView.header endRefreshing];
        KDLog(@"%@",error);
    }];
    
}
- (void)loadMoreDetailData{
    self.page = [NSString stringWithFormat:@"%ld",self.page.integerValue+1];
    //    KDSubscribeListParam *param = [[KDSubscribeListParam alloc]init];
    self.param.page = self.page;
    self.param.keyword = self.keyword;
    //    self.param.method = @"earlywaring/queryEarlyWaringPushInfo";
    //    self.param.aboutType = [NSString stringWithFormat:@"%ld",self.model.ID];
    //    param.limit = @"10";
    [KDSubscripRequestTool getSubscribeListWithParam:self.param success:^(KDGetSubscribeListResult *responseObejct) {
        if ([responseObejct.code isEqualToString:@"1"]) {
            if (responseObejct.data.count) {
                NSMutableArray *arr = [NSMutableArray arrayWithArray:self.infoArr];
                [arr addObjectsFromArray:responseObejct.data] ;
                self.infoArr = arr;
                [self.tableView reloadData];
                [self.tableView.footer endRefreshing];
            }else{
                [self.tableView reloadData];
                [self.tableView.footer noticeNoMoreData];
            }
            
        }else{
            [SVProgressHUD showErrorWithStatus:responseObejct.msg maskType:SVProgressHUDMaskTypeGradient];
        }
    } failure:^(NSError *error) {
        [self.tableView.footer endRefreshing];
        [SVProgressHUD showErrorWithStatus:@"网络错误！" maskType:SVProgressHUDMaskTypeGradient];
        KDLog(@"%@",error);
    }];
    
}
#pragma mark - 通知接收区


#pragma mark - 🔌 UITableViewDataSource Method

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (self.isShowResults) {
        self.navigationController.view.backgroundColor = BACKGROUND_COLOR;
        return self.infoArr.count;
    } else {
        self.navigationController.view.backgroundColor = [UIColor clearColor];
        return self.searchHistories.count;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.isShowResults) {
        KDSubscribCell *cell = [KDSubscribCell cellWithTableView:tableView];
        //    KDLog(@"waimian%d", indexPath.row);
        cell.delegate = self;
        if (tableView == self.tableView)
        {
            cell.delegate = self;
            if (self.infoArr.count != 0)
            {
                cell.model = self.infoArr[indexPath.row];
            }
            return cell;
        }else{
            return cell;
        }
    } else {
        static NSString *searchHistoryTableView = @"searchHistoryTableView";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:searchHistoryTableView];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:searchHistoryTableView];
            [cell.contentView addSubLayerWithFrame:CGRectMake(0,
                                                              44 - 0.5f,
                                                              [UIScreen mainScreen].bounds.size.width,
                                                              0.5f
                                                              )
                                             color:TABLE_LINE_COLOR];
            cell.textLabel.backgroundColor = [UIColor whiteColor];
        }
        cell.imageView.image = [UIImage imageNamed:@"SearchHistory"];
        cell.textLabel.text = self.searchHistories[indexPath.row];
        cell.textLabel.font = [UIFont systemFontOfSize:14];
        UIButton *rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        rightBtn.frame = CGRectMake([UIScreen mainScreen].bounds.size.width - 44, 0, 44, 44);
        // 监听点击删除按钮
        [rightBtn addTarget:self action:@selector(rightBtnDidClicked:) forControlEvents:UIControlEventTouchUpInside];
        [rightBtn setImage:[UIImage imageNamed:@"search_history_delete_icon_normal"] forState:UIControlStateNormal];
        [rightBtn setImage:[UIImage imageNamed:@"SearchDeleteSelected"] forState:UIControlStateSelected];
        rightBtn.tag = indexPath.row;
        [cell.contentView addSubview:rightBtn];
        return cell;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.isShowResults) {
        return Cell_h;
    } else {
        return 44;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if(self.isShowResults){
        return 44;
    }
    return kMinTableViewHeight;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    if (!self.isShowResults && self.searchHistories.count > 0) {
        return kHeightForFooterInSection;
    }
    return kMinTableViewHeight;
}

#pragma mark - 🔌 UITableViewDelegatel Method

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    if (!self.isShowResults && self.searchHistories.count>0) {
        UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, kHeightForFooterInSection)];
        footerView.backgroundColor = [UIColor whiteColor];
        UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(([UIScreen mainScreen].bounds.size.width - 160)/2, 18, 160, 30)];
        [footerView addSubview:btn];
        [btn setBackgroundColor:[UIColor whiteColor]];
        btn.layer.borderWidth = 0.5;
        btn.layer.borderColor =[UIColor lightGrayColor].CGColor;
        btn.layer.cornerRadius = 4;
        [btn setTitle:@"清除搜索历史" forState:UIControlStateNormal];
        btn.titleLabel.font = [UIFont fontWithName:@"Superclarendon-Light" size:16];
        [btn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
        [btn addTarget:self action:@selector(clearHistoriesButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
        return footerView;
    }
    return nil;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.isShowResults) {
        
        if (tableView == self.tableView) {
            if (self.infoArr.count == 0) {
                return;
            }
            KDSubscribCell *cell = (KDSubscribCell *)[tableView cellForRowAtIndexPath:indexPath];
            NSMutableArray *arr = [NSMutableArray arrayWithArray:self.infoArr];
            [arr replaceObjectAtIndex:indexPath.row withObject:cell.model];
            self.infoArr = arr;
            KDDetailSubscribController *singleCtrl = [[KDDetailSubscribController alloc]init];
            singleCtrl.delegate = self;
            singleCtrl.model = cell.model;
            
            self.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:singleCtrl animated:YES];
            self.hidesBottomBarWhenPushed = NO;
            
        }
    } else {
        self.searchBar.text = self.searchHistories[indexPath.row];
        KDLog(@"%@",self.searchBar.text);
        self.keyword = self.searchHistories[indexPath.row];
        [self getResultsList:nil];
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *header;
    if(self.isShowResults)
    {
        header = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 44)];
        header.backgroundColor = [UIColor whiteColor];
        [header addSubview:self.titleLabel];
        self.titleLabel.text = [NSString stringWithFormat:@"与%@有关的搜索结果", self.keyword];
        
        UIView *cureLine = [[UIView alloc] initWithFrame:CGRectMake(12, 43.5, [UIScreen mainScreen].bounds.size.width - 12, 0.5)];
        cureLine.backgroundColor = [UIColor colorWithRed:224/255.f green:224/255.f blue:224/255.f alpha:1.f];
        [header addSubview:cureLine];
    }
    return header;
}


#pragma  mark - UISearchBarDelegate
/**
 *  点击输入框，显示搜索记录
 */
- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar{
    self.searchBar.text = @"";
    if (self.isShowResults) {
        //如果是
        self.showResults = NO;
        [self reloadViewLayouts];
    }
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    if (searchBar.text.length == 0) {
        return;
    }
    if ([self.searchHistories containsObject:searchBar.text]) {
        [self.searchHistories removeObject:searchBar.text];
    }
    // 保存搜索记录，最多10条
    [self.searchHistories insertObject:searchBar.text atIndex:0];
    self.keyword = searchBar.text;
    if (self.searchHistories.count > kMostNumberOfSearchHistories) {
        [self.searchHistories removeLastObject];
    }
    [[NSUserDefaults standardUserDefaults] setObject:self.searchHistories forKey:self.kSearchHistory];
    [[NSUserDefaults standardUserDefaults] synchronize];
//    KDLog(<#...#>)
    // 开始搜索
    [self getResultsList:nil];
    [self reloadViewLayouts];
}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
    if (_delegate && [_delegate respondsToSelector:@selector(questionSearchCancelButtonClicked:)]) {
        [_delegate questionSearchCancelButtonClicked:self];
    }
}

/**
 *  一旦滑动列表，隐藏键盘
 */
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (self.searchBar.isFirstResponder) {
        [self.searchBar resignFirstResponder];
    }
}

# pragma mark - KDSubscribCellDelegate
- (void)subscribCell:(KDSubscribCell *)cell collectBtnClick:(UIButton *)collectBtn{
    //0.先判断是点击的收藏还是取消收藏
    if (collectBtn.selected) {//说明是要取消收藏
        [self cancelFavarWithCell:cell andCollectBtn:collectBtn];
    }else{//添加收藏
        [self addFavarWithCell:cell andCollectBtn:collectBtn];
    }
    
    
}
/**
 *  取消收藏 */
- (void)cancelFavarWithCell:(KDSubscribCell *)cell andCollectBtn:(UIButton *)collectBtn{
    __weak __typeof(self)weakSelf = self;
    NSIndexPath *index = [self.tableView indexPathForCell:cell];
    KDFavorParam *param = [[KDFavorParam alloc]init];
    param.info_id = [NSString stringWithFormat:@"%ld",cell.model.ID];
    
    [KDCollectRequestTool cancelFavorMsgWithParam:param success:^(KDBaseResult *responseObejct) {
        if ([responseObejct.code isEqualToString:@"1"]) {
            [SVProgressHUD showSuccessWithStatus:@"取消收藏成功" maskType:SVProgressHUDMaskTypeGradient];
            collectBtn.selected = NO;
            KDSubscribCellModel *model = weakSelf.infoArr[index.row];
            //                        NSMutableArray *muteArr = [NSMutableArray arrayWithArray:weakSelf.infoArr];
            model.isCollection = NO;
        }else{
            [SVProgressHUD showErrorWithStatus:responseObejct.msg maskType:SVProgressHUDMaskTypeGradient];
        }
    } failure:^(NSError *error) {
        [SVProgressHUD showErrorWithStatus:@"网络错误！" maskType:SVProgressHUDMaskTypeGradient];
    }];
}
/**
 *  添加收藏的一系列操作
 *
 *  @param cell
 */
- (void)addFavarWithCell:(KDSubscribCell *)cell andCollectBtn:(UIButton *)collectBtn{
    __weak __typeof(self)weakSelf = self;
    NSIndexPath *index = [self.tableView indexPathForCell:cell];
    //1.弹出收藏夹列表（需要一个拉取收藏夹列表请求）
    KDBaseParam *param = [[KDBaseParam alloc]init];
    //    param.method = @"collection/type/myCollectionType";
    [KDCollectRequestTool getFavorTypeListWithParam:param success:^(KDFavorTypeListResult *responseObejct) {
        if ([responseObejct.code isEqualToString:@"1"]) {
            AlertTableView *modelView = [[AlertTableView alloc] init];
            __weak typeof(AlertTableView) *weakModelView =modelView;
            
            modelView.modalPresentationStyle = UIModalPresentationOverCurrentContext;
            modelView.modalTransitionStyle =  UIModalTransitionStyleCrossDissolve;
            modelView.AlertFromDirect = fromDirectCenter;
            modelView.titleString = @"收藏夹列表";
            modelView.rowHight = 45;
            modelView.viewState = viewStateGray;
            modelView.AlertArray = responseObejct.data;
            
            modelView.doneBtnClickWithType = ^(KDFavorType *selectTyle){
                //2.选中一个收藏夹，返回被选中的文件夹的model！
                KDFavorParam *param = [[KDFavorParam alloc]init];
                param.info_id = [NSString stringWithFormat:@"%ld",cell.model.ID];
                param.post_time = cell.model.craw_publishtime;
                param.type_id = [NSString stringWithFormat:@"%ld", selectTyle.type_id];
                param.url = cell.model.craw_url;
                param.website_name = cell.model.site_name;
                param.author = cell.model.craw_author;
                param.emotionType = [NSString stringWithFormat:@"%ld", cell.model.analy_posneg];
                param.title = cell.model.craw_title;
                
                //3.添加收藏！
                [KDCollectRequestTool addFavorMsgWithParam:param success:^(KDBaseResult *result) {
                    if ([result.code isEqualToString:@"1"]) {
                        [SVProgressHUD showSuccessWithStatus:responseObejct.msg maskType:SVProgressHUDMaskTypeGradient];
                        collectBtn.selected = YES;
                        KDSubscribCellModel *model = weakSelf.infoArr[index.row];
                        model.isCollection = YES;
                        
                        [weakModelView dismissSelfView];
                    }else{
                        [SVProgressHUD showErrorWithStatus:responseObejct.msg maskType:SVProgressHUDMaskTypeGradient];
                    }
                } failure:^(NSError *error) {
                    [SVProgressHUD showErrorWithStatus:@"网络错误！" maskType:SVProgressHUDMaskTypeGradient];
                }];
            };
            
            [weakSelf presentViewController:modelView animated:YES completion:nil];
        }else{
            [SVProgressHUD showErrorWithStatus:responseObejct.msg maskType:SVProgressHUDMaskTypeGradient];
        }
    } failure:^(NSError *error) {
        [SVProgressHUD showErrorWithStatus:@"网络错误！" maskType:SVProgressHUDMaskTypeGradient];
    }];
}
/**
 *  上报按钮被点击了
 */
- (void)subscribCell:(KDSubscribCell *)cell reportBtnClick:(UIButton *)reportBtn{
    KDReportController *reportCtrl = [[KDReportController alloc]init];
    KDSubscribCellModel *model = cell.model;
    KDPatrolgetReportParam *param = [[KDPatrolgetReportParam alloc]init];
    param.url = model.craw_url;
    param.info_title = model.craw_title;
    param.info_content = model.craw_content;
    param.website_type = model.site_type;
    param.website_name = model.site_name;
    reportCtrl.param = param;
//    reportCtrl.type = 1;
    reportCtrl.delegate = self;
    [self.navigationController pushViewController:reportCtrl animated:YES];
}

- (void)subscribCell:(KDSubscribCell *)cell instructBtnClick:(UIButton *)collectBtn{
    
    KDDetailSubscribController *singleCtrl = [[KDDetailSubscribController alloc]init];
    singleCtrl.delegate = self;
    singleCtrl.model = cell.model;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.7 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        //        [singleCtrl jumpToComment];
        
    });
    self.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:singleCtrl animated:YES];
    self.hidesBottomBarWhenPushed = NO;
}

- (void)subscribCell:(KDSubscribCell *)cell deleteBtnClick:(UIButton *)deleteBtn{
    WS(ws);
    NSMutableArray *arr = [NSMutableArray arrayWithArray:self.infoArr];
    NSIndexPath *ip = [self.tableView indexPathForCell:cell];
    //开启选择界面
    [KGDislikeView showFromView:cell items:[DislikeModel readDislikeReasons] dislikeBlock:^(KGDislikeView *dislikeView, KDDeleteNewsParam *param) {//选完删除原因之后回来会调用这里
        param.ID =[NSString stringWithFormat:@"%ld",  cell.model.ID];
        [SVProgressHUD showWithStatus:@"删除中..." maskType:SVProgressHUDMaskTypeGradient];
        [KDCollectRequestTool deleteNewsWithParam:param success:^(KDBaseResult *responseObejct) {
            if ([responseObejct.code isEqualToString:@"1"]) {
                [SVProgressHUD dismiss];
                [arr removeObjectAtIndex:ip.row];
                ws.infoArr = arr;
                [ws.tableView deleteRowsAtIndexPaths:@[ip]withRowAnimation:UITableViewRowAnimationAutomatic];
            }else{
                [SVProgressHUD showErrorWithStatus:responseObejct.msg maskType:SVProgressHUDMaskTypeGradient];
            }
        } failure:^(NSError *error) {
            [SVProgressHUD showErrorWithStatus:@"网络错误!" maskType:SVProgressHUDMaskTypeGradient];
        }];
        
        
    }];
}
#pragma mark - KDDetailSubscribControllerDelegate
- (void)backFromDetailSubscribCtrWithModel:(KDSubscribCellModel *)model{
    int index = 0;
    NSMutableArray *arr = [NSMutableArray arrayWithArray:self.infoArr];
    for (KDSubscribCellModel *cellModel in self.infoArr) {
        if (cellModel.ID == model.ID) {
            [arr replaceObjectAtIndex:index withObject:model];
            break;
        }
        index++;
    }
    self.infoArr = arr;
    [self.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:index inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
}


@end
